import * as fs from 'fs';
import * as path from 'path';
import { isExistFile, getFilePath } from '../util';


export default {
  match: /(?<!(\.d))\.(ts|js|tsx|jsx)$/,
  excludes: ['node_modules', 'dist', 'public'],

  parse: function (file: string, externals: any): Array<string> {
    try {
      if (fs.statSync(file).isDirectory()) {
        return [];
      }
      const filedata = fs.readFileSync(file, { encoding: 'utf8' });
      const matchs = filedata.match(/(import[^\;]+\;)|(export(.+)from[^\;]+\;)|(import(.+)from[^\;]+\;)|(require\([^\;]+\;)/gi) || [];
      return matchs.map((val) => {
        const relayFile: string = val.replace(/\'/g, '"').split('"')[1];
        if (relayFile.indexOf('.') === 0) {
          return getFilePath(path.join(file, '..', relayFile));
        } else {
          for (const i in externals) {
            const element = externals[i];
            if (relayFile.indexOf(i) === 0) {
              let filepath;
              for (let j = 0; j < element.length; j++) {
                const e = element[j];
                filepath = getFilePath(path.join(e, relayFile.replace(i, '')));
                if (filepath) {
                  return filepath;
                }
              }
            }
          }
          return relayFile;
        }
      });

    } catch (e) {
      console.log('e', file);
    }
    return [];
  },
  getExternals: function (rootPath: string) {
    const externals: any = {};
    // tsconfig.json
    const tsconfigFile = path.join(rootPath, 'tsconfig.json');
    if (isExistFile(tsconfigFile)) {
      const tsconfig = eval(`const $config = ${fs.readFileSync(tsconfigFile).toString()}; $config`);
      const paths = tsconfig.compilerOptions.paths;
      const baseUrl = tsconfig.compilerOptions.baseUrl;
      if (paths) {
        for (const i in paths) {
          const element: Array<string> = paths[i];
          if (i.lastIndexOf("/*") === i.length - 2) {
            const _i = i.substring(0, i.length - 2);
            if (paths[_i]) {
              paths[_i] = void 0;
            }
            externals[_i] = element.map((val => path.join(rootPath, baseUrl, val.substring(0, val.length - 2))));
          } else {
            if (element) {
              externals[i] = element.map((val => path.join(rootPath, baseUrl, val)));
            }
          }
        }
      }
    }
    return externals;
    // webpack.config.json
    //  const webpackFile = path.join(rootPath, ' webpack.config.js');

  }
};
